<?php
/**
 * AannouncementController
 * 
 * @author
 * @version 
 */
require_once 'Zend/Controller/Action.php';
class AannouncementController extends Zend_Controller_Action
{
    protected $_announcementModel;
	
	public function init()
	{
	    $authService = new Eleven_Service_Authentication();
	           
	    if ($authService->getIdentity()->role != 'Teacher') {
	        $this->_helper->redirector('index','index');
	    }
	    
		$this->_announcementModel = new Eleven_Model_Announcement();
		
		$this->view->controller = $this->_request->controller;
		//$this->view->editForm = $this->getEditForm();
	}
	
    /**
     * The default action - show the home page
     */
    public function indexAction ()
    {    
        $announcements = $this->_announcementModel->getAnnouncements ( $this->_getParam ( 'page', 1 ), array ('publishdate DESC' ) );
		
		$this->view->assign(array('announcements'=>$announcements));
    }
    
    public function editAction()
    {
        $this->view->editForm = $this->getEditForm($this->_getParam('announcementId'));
    }
    
    public function getEditForm($announcementId)
	{
		$urlHelper = $this->_helper->getHelper('url');

        $this->_forms['edit'] = $this->_announcementModel->getForm('announcementEdit');
        $this->_forms['edit']->setAction($urlHelper->url(array('action' => 'save')));
        
        $this->_forms['edit']->setMethod('post');
        
        $announcement = $this->_announcementModel->getAnnounceById($announcementId);
        
        $this->_forms['edit']->getElement('id')->setValue($announcement->id);
        $this->_forms['edit']->getElement('title')->setValue($announcement->title);
        $this->_forms['edit']->getElement('content')->setValue($announcement->content);
        return $this->_forms['edit'];
	}
	
	public function saveAction()
	{
	    $request = $this->getRequest();
		if (!$request->isPost()) 
		{
			return $this->_helper->redirector('index');
  		}
  		
  		if (false === $this->_announcementModel->saveEdit($request->getPost())) 
  		{
     		return $this->render('edit');
  		}
  		
  		return $this->_helper->redirector('index');
	}
	
	public function deleteAction()
	{
	    if ($this->_announcementModel->deleteAnnounceById ( $this->_getParam ( 'announcementId' )))
	    {
	        return $this->_helper->redirector('index');
	    }else{
	        return $this->_helper->redirector('index');
	    }
	}
	
	public function topAction()
	{
        $tops = $this->_request->getParam('select');
        if (count($tops))
        {
            $this->_announcementModel->setTops($tops);
        }else {
            $tops = array($this->_request->getParam('id'));
            $this->_announcementModel->setTops($tops, true);
        }
        
        return $this->_helper->redirector('index');
	}
}

